String Function

Course- PHP TUTOTRIAL >

PHP - String Position - strpos

Being able to manipulate strings is a valuable skill, especially in PHP. You'll most likely come across a programming problem that requires you to find some data in a string. The beginning of a lot of your string manipulation expertise will begin with the strpos function, which allows you to find data in your string.

Searching a String with strpos

The way strpos works is it takes some string you want to search in as its first argument and another string, which is what you are actually searching for, as the second argument. If the function can find a search match, then it will return the position of the first match. However, if it can't find a match it will return false.

To make this function crystal clear, lets search a numbered, in-order string, for the number five.

PHP Code:

$numberedString = "1234567890"; // 10 numbers from 1 to 0

$fivePos = strpos($numberedString, "5");
echo "The position of 5 in our string was $fivePos";

Display:

The position of 5 in our string was 4

Notice that the position is 4, which may seem confusing at first, until you realize that PHP starts counting from 0.

  • The number 1 - Position 0 - No match
  • The number 2 - Position 1 - No match
  • The number 3 - Position 2 - No match
  • The number 4 - Position 3 - No match
  • The number 5 - Position 4 - Match

Although we only searched for a single character, you can use this function to search for a string with any number of characters. Also, it is important to note that this function will return the position of the start of the first match. So if we had searched the same string for "567890" we would again find a match and position 4 because that is where the match starts.

Finding All Occurrences in a String with Offset

One of the limitations of strpos is that it only returns the position of the very first match. If there are 5,000 other matches in the string you would be none the wiser, unless you take action!

There is a third (optional) argument to strpos that will let you specify where to begin your search of the string. If you were to store the position of the last match and use that + 1 as an offset, you would skip over the first match and be find the next one.

PHP Code:

$numberedString = "1234567890123456789012345678901234567890";

$fivePos = strpos($numberedString, "5");
echo "The position of 5 in our string was $fivePos";
$fivePos2 = strpos($numberedString, "5", $fivePos + 1);
echo "<br />The position of the second 5 was $fivePos2";

Display:

The position of 5 in our string was 4
The position of the second 5 was 14

By taking the first match's position of 4 and adding 1 we then asked strpos to begin searching after the last match. The string it was actually searching after computing the offset was: 6789012345... Letting us find the second 5 in the string.

If we use our knowledge of PHP While Loops we can find every single 5 in our string numberedString with just a few lines of code.

PHP Code:

$numberedString = "1234567890123456789012345678901234567890";
$offset = 0; // initial offset is 0
$fiveCounter = 0;

// First check if there is a "5" at position 0.
if(strpos($numberedString, "5") == 0){
	$fiveCounter++;
	echo "<br />Five #$fiveCounter is at position - 0";
}

// Check the rest of the string for 5's
while($offset = strpos($numberedString, "5", $offset + 1)){
	$fiveCounter++;
	echo "<br />Five #$fiveCounter is at position - $offset";
}

Display:

Five #1 is at position - 4
Five #2 is at position - 14
Five #3 is at position - 24
Five #4 is at position - 34

That conditional statement in our while loop may look a little intimidating, but not if you break it down.

  • $offset = strpos($numberedString, "5", $offset + 1) - This is our conditional statement for our PHP While Loop. If this ever is false the while loop will stop running. This conditional statement always runs before each pass through the while loop.
  • strpos($numberedString, "5", $offset + 1) - This is the same code we used in a previous example. We are going to search our string numberedString for the number 5 and use the last match's value (stored in $offset) + 1 to skip over the last match. The first $offset we use has a value of 0, so that we start at the beginning of the string.
  • $offset = strpos(... We are going to store the location returned by strpos into $offset so that we can skip this match the next time the while loop runs through the code. If strpos ever fails to find a match then this will be set to false making our while loop stop executing.

PHP str_replace Function

Another key tool to have in your programming toolbox is the ability to quickly replace parts of a PHP string with new values. The str_replace function is similar to a word processor's "Replace All" command that lets you specify a word and what to replace it with, then replaces every occurrence of that word in the document.

str_replace Parameters

str_replace has three parameters that are required for the function to work properly. str_replace(search, replace, originalString).

  1. search - This is what you want to search your string for. This can be a string or an array.
  2. replace - All matches for search will be replaced with this value. This can be a string or an array.
  3. originalString - This is what search and replace will be operating on. The str_replace function will return a modified version of originalString when it completes.

str_replace Simple Example

Imagine we are working at a school district and need to create a webpage for the students' parents. The webpage has an introduction string that we need to customize depending on if the student is male or female. With str_replace this is mighty easy.

PHP Code:

//string that needs to be customized
$rawstring = "Welcome Birmingham parents. Your replaceme is a pleasure to have!";

//male string
$malestr = str_replace("replaceme", "son", $rawstring);

//female string
$femalestr = str_replace("replaceme", "daughter", $rawstring);

echo "Son: ". $malestr . "<br />";
echo "Daughter: ". $femalestr;

Display:

Son: Welcome Birmingham parents. Your son is a pleasure to have!
Daughter: Welcome Birmingham parents. Your daughter is a pleasure to have!

With these two gender customized strings created we could then provide a more engaging experience for the student's parents when they logged into the school website with their kid's credentials.

str_replace Arrays: Multiple Replaces in One

In the last example we only needed to replace one word replaceme in our string, but what if we wanted to replace many words? We could just use the function multiple times to get the job done, or we could create an array of placeholders and a second array of replace values to get it all done in one function call.

The key thing to understand with this technique is that you are creating two arrays that will be used to swap values. The first item in placeholders will be replaced by the first item in the replace values, the second item of placeholders replaced with the second in replace values and so on and so forth.

Let's extend our simple example to be a complete form letter addressed to a student's parents.

PHP Code:

//string that needs to be customized
$rawstring = "Welcome Birmingham parent! <br />
	Your offspring is a pleasure to have! 
	We believe pronoun is learning a lot.<br />
	The faculty simple adores pronoun2 and you can often hear 
	them say \"Attah sex!\"<br />";

//placeholders array
$placeholders = array('offspring', 'pronoun', 'pronoun2', 'sex');
//male replace values array
$malevals = array('son', 'he', 'him', 'boy');
//female replace values array
$femalevals = array('daughter', 'she', 'her', 'girl');

//male string
$malestr = str_replace($placeholders, $malevals, $rawstring);

//female string
$femalestr = str_replace($placeholders, $femalevals, $rawstring);

echo "Son: ". $malestr . "<br />";
echo "Daughter: ". $femalestr;

Display:

Son: Welcome Birmingham parent!
Your son is a pleasure to have! We believe he is learning a lot.
The faculty simple adores he2 and you can often hear them say "Attah boy!"

Daughter: Welcome Birmingham parent!
Your daughter is a pleasure to have! We believe she is learning a lot.
The faculty simple adores she2 and you can often hear them say "Attah girl!"

Notice: there is a bug in this code. The placeholder pronoun2 did not get replaced in the way we intended (our strings have he2 and she2 instead of him and her). This is because all instances of pronoun were replaced first and the pronoun in pronoun2 was replaced at this time with he or she, making he2 or she2. When it was pronoun2's turn to be replaced, there were no matches to be found, so our string has no him or her.

To fix this bug you could simply make sure that pronoun2 comes first in the placeholders array and by updating the values of the male and female replace values to reflect this.

PHP Code:

// ...snip
//placeholders array
$placeholders = array('offspring', 'pronoun2', 'pronoun',  'sex');
//male replace values array
$malevals = array('son', 'him', 'he',  'boy');
//female replace values array
$femalevals = array('daughter', 'her', 'she',  'girl');
//snip...

Display:

Son: Welcome Birmingham parent!
Your son is a pleasure to have! We believe he is learning a lot.
The faculty simple adores him and you can often hear them say "Attah boy!"

Daughter: Welcome Birmingham parent!
Your daughter is a pleasure to have! We believe she is learning a lot.
The faculty simple adores her and you can often hear them say "Attah girl!"

substr_replace's Four Parameters

There are three required parameters for the substr_replace function (original string, replacement string, starting point) and one that's optional (length).

  1. original string - This is your original string that will be operated on.
  2. replacement string - This string will be used to replace everything in the string from the starting point to the ending point (specified by length).
  3. starting point - This is the place in the original string that will be used to mark the replacement's beginning. A negative value specifies the number of characters from the end of the string.
  4. optional length - How many characters from the original string will be replaced. If no length is specified then the end of the string is used. If a value of 0 is used then no characters will be replaced and an insert is performed. A negative value specifies the number of characters from the end of the string.

substr_replace On Your Mark

This example of substr_replace shows what happens when you omit the length parameter at various starting points.

PHP Code:

//string that needs to be customized
$original = "ABC123 Hello Mr. Cow! DEF321";

//starting point 5
$sp5 = substr_replace($original, "Five", 5);
//starting point 12
$sp12 = substr_replace($original, "Twelve", 12);
//starting point 0
$sp0 = substr_replace($original, "Zero", 0);
//starting point -1
$spneg1 = substr_replace($original, "Negative 1", -1);

//Echo each string
echo "Original String: $original <br />";
echo "Starting Point 5: $sp5 <br />";
echo "Starting Point 12: $sp12 <br />";
echo "Starting Point 0: $sp0 <br />";
echo "Starting Point -1: $spneg1 ";

Display:

Original String: ABC123 Hello Mr. Cow! DEF321
Starting Point 5: ABC12Five
Starting Point 12: ABC123 HelloTwelve
Starting Point 0: Zero
Starting Point -1: ABC123 Hello Mr. Cow! DEF32Negative 1

As you can see, when you don't specify the fourth parameter, length, everything after the starting point is replaced by the second parameter replacement string.

Note: The first replacement occurred at position 5, which in $original was the character 3. This 3 and everything onward was replaced with the replacement string. Remember that you start counting character to begin from zero. The $original string could be labeled as so:

  • Letter A - Position 0
  • Letter B - Position 1
  • Letter C - Position 2
  • Letter 1 - Position 3
  • Letter 2 - Position 4
  • Letter 3 - Position 5

substr_replace Specifying a Length

If you want to get any sort of precision out of this function you're going to have to get into the nitty gritty of specifying the exact length of characters you want replaced in your original string.

Imagine that you want to get rid of those ugly pseudo references (ABC123, DEF321) at the beginning and end of the string. Since both of those strings are a length of 6 and we know one is at the very beginning of the string and the other is at the very end of the string we should probably use a starting point of 0 for ABC123 and a value of -6 for DEF321. By having a replacement string of nothing "" we can do something similar to select and delete that we often do in a word processor.

PHP Code:

//string that needs to be customized
$original = "ABC123 Hello Mr. Cow! DEF321";

//remove ABC123 and store in $cleanedstr
$cleanedstr = substr_replace($original, "", 0, 6);
//remove DEF321 from $cleanedstr
$cleanedstr2 = substr_replace($cleanedstr, "", -6, 6);

//Echo each string
echo "Original String: $original <br />";
echo "Clean #1: $cleanedstr <br />";
echo "Clean #2: $cleanedstr2";

Display:

Original String: ABC123 Hello Mr. Cow! DEF321
Clean #1: Hello Mr. Cow! DEF321
Clean #2: Hello Mr. Cow!

Make sure that you play around with this function some on your own so you can get a feel for how the starting point and length parameters effect this function.

substr_replace Perform an Insert

By setting the length parameter to zero you can stop substr_replace from removing anything from the original string and just add to it. If we wanted to add a second and third person to our $original string we would want to do this insert operation. Note: instead of counting the characters we've used a couple other PHP functions to figure out the starting positions for us.

PHP Code:

//string that needs to be customized
$original = "Hello Mr. Cow!";

// Get the position of Mr. Cow
$cowpos = strpos($original, "Mr. Cow");

// Find where Mr. Cow ends by adding the length of Mr. Cow
$cowpos_end = $cowpos + strlen("Mr. Cow");

// Insert Mrs. Bear after Mr. Cow
$mrsbear = substr_replace($original, " and Mrs. Bear", $cowpos_end, 0);

// Insert Sensei Shark before Mr. Cow
$senseishark = substr_replace($mrsbear, "Sensei Shark, ", $cowpos, 0);


//Echo each string
echo "Original String: $original <br />";
echo "After Mrs. Bear: $mrsbear <br />";
echo "After Sensei Shark: $senseishark";

Display:

Original String: Hello Mr. Cow!
After Mrs. Bear: Hello Mr. Cow and Mrs. Bear!
After Sensei Shark: Hello Sensei Shark, Mr. Cow and Mrs. Bear!

We snuck a new function strlen into that example, but it isn't that complicated of a function, as it stands for "string length."

  • $cowpos_end = $cowpos + strlen("Mr. Cow");

The strlen function takes a string and then counts up how many characters are in it then returns that number. So by calculating the length of "Mr. Cow" and adding that to the position, we find out where the end point is!



PHP - String Capitalization Functions

If you've ever wanted to manipulate the capitalization of your PHP strings, then this lesson will be quite helpful to you. PHP has three primary capitalization related functions: strtoupper, strtolower and ucwords. The function names are pretty self-explanatory, but why they are useful in programming might be new to you.

Converting a String to Upper Case - strtoupper

The strtoupper function takes one argument, the string you want converted to upper case and returns the converted string. Only letters of the alphabet are changed, numbers will remain the same.

PHP Code:

$originalString = "String Capitalization 1234"; 

$upperCase = strtoupper($originalString);
echo "Old string - $originalString <br />";
echo "New String - $upperCase";

Display:

Old string - String Capitalization 1234
New String - STRING CAPITALIZATION 1234

One might use this function to increase emphasis of a important point or in a title. Another time it might be used with a font that looks very nice with all caps to fit the style of the web page design.

A more technical reason would be to convert two strings you are comparing to see if they are equal. By converting them to the same capitalization you remove the possibility that they won't match simply because of different capitalizations.

Converting a String to Lower Case - strtolower

The strtolower function also has one argument: the string that will be converted to lower case.

PHP Code:

$originalString = "String Capitalization 1234"; 

$lowerCase = strtolower($originalString);
echo "Old string - $originalString <br />";
echo "New String - $lowerCase";

Display:

Old string - String Capitalization 1234
New String - string capitalization 1234

Capitalizing the First Letter - ucwords

Titles of various media types often capitalize the first letter of each word and PHP has a time-saving function that will do just this.

PHP Code:

$titleString = "a title that could use some hELP"; 

$ucTitleString = ucwords($titleString);
echo "Old title - $titleString <br />";
echo "New title - $ucTitleString";

Display:

Old title - a title that could use some hELP
New title - A Title That Could Use Some HELP

Notice that the last word "hELP" did not have the capitalization changed on the letters that weren't first, they remained capitalized. If you want to ensure that only the first letter is capitalized in each word of your title, first use the strtolower function and then the ucwords function.

PHP Code:

$titleString = "a title that could use some hELP"; 

$lowercaseTitle = strtolower($titleString);
$ucTitleString = ucwords($lowercaseTitle);
echo "Old title - $titleString <br />";
echo "New title - $ucTitleString";

Display:

Old title - a title that could use some hELP
New title - A Title That Could Use Some Help



  1. Hello,
  2. I
  3. would
  4. like
  5. to
  6. lose
  7. weight.

The dynamite (the space character) disappears, but the other stuff remains, but in pieces. With that abstract picture of the explode function in mind, lets take a look at how it really works.

The explode Function

The first argument that explode takes is the delimiter (our dynamite) which is used to blow up the second argument, the original string. explode returns an array of string pieces from the original and they are numbered in order, starting from 0. Lets take a phone number in the form ###-###-#### and use a hyphen "-" as our dynamite to split the string into three separate chunks.

PHP Code:

$rawPhoneNumber = "800-555-5555"; 

$phoneChunks = explode("-", $rawPhoneNumber);
echo "Raw Phone Number = $rawPhoneNumber <br />";
echo "First chunk = $phoneChunks[0]<br />";
echo "Second chunk = $phoneChunks[1]<br />";
echo "Third Chunk chunk = $phoneChunks[2]";

Display:

Raw Phone Number = 800-555-5555
First chunk = 800
Second chunk = 555
Third Chunk chunk = 5555

explode Function - Setting a Limit

If you want to control the amount of destruction that explode can wreak on your original string, consider using the third (optional) argument which allows you to set the number of pieces explode can return. This means it will stop exploding once the number of pieces equals the set limit. Below we've blown up a sentence with no limit and then with a limit of 4.

PHP Code:

$someWords = "Please don't blow me to pieces."; 

$wordChunks = explode(" ", $someWords);
for($i = 0; $i < count($wordChunks); $i++){
	echo "Piece $i = $wordChunks[$i] <br />";
}

$wordChunksLimited = explode(" ", $someWords, 4);
for($i = 0; $i < count($wordChunksLimited); $i++){
	echo "Limited Piece $i = $wordChunksLimited[$i] <br />";
}

Display:

Piece 0 = Please
Piece 1 = don't
Piece 2 = blow
Piece 3 = me
Piece 4 = to
Piece 5 = pieces.
Limited Piece 0 = Please
Limited Piece 1 = don't
Limited Piece 2 = blow
Limited Piece 3 = me to pieces.

The limited explosion has 4 pieces (starting from 0, ending at 3). If you forgot how a for loop works, check out PHP For Loops.



PHP - Array implode

The PHP function implode operates on an array and is known as the "undo" function of explode. If you have used explode to break up a string into chunks or just have an array of stuff you can use implode to put them all into one string.

PHP implode - Repairing the Damage

The first argument of implode is the string of characters you want to use to join the array pieces together. The second argument is the array (pieces).

PHP Code:

$pieces = array("Hello", "World,", "I", "am", "Here!");

$gluedTogetherSpaces = implode(" ", $pieces);
$gluedTogetherDashes = implode("-", $pieces);
for($i = 0; $i < count($pieces); $i++){
	echo "Piece #$i = $pieces[$i] <br />";
}
echo "Glued with Spaces = $gluedTogetherSpaces <br />";
echo "Glued with Dashes = $gluedTogetherDashes";

Display:

Piece #0 = Hello
Piece #1 = World,
Piece #2 = I
Piece #3 = am
Piece #4 = Here!
Glued with Spaces = Hello World, I am Here!
Glued with Dashes = Hello-World,-I-am-Here!

The implode function will convert the entire array into a string and there is no optional argument to limit this as there was in the explode function.